var fs=require('fs')
var path=require('path')

const crypto = require("crypto");
//最大长度
var maxlen=100;
function Namen(name){
	name=encodeURIComponent(name)
		var md5 = crypto.createHash('md5');  
		var message = 'hello';
		var codes = md5.update(name, 'utf8').digest('hex'); //hex转化为十六进制
if(codes.length>=maxlen)
	codes=codes.slice(0,maxlen)+'=='+codes.length
	
	return codes.toLowerCase().replace(/%/g,'');
}


function saveImg(imgData,name){
	//过滤data:URL
	var _arr=imgData.split(',')
	var base64Data = _arr[1];
	var mime = _arr[0].match(/:(.*?);/)[1].split('/')[1];
	var src=path.join(__dirname,'../../public','images','heads')
	var url=path.join(src,Namen(name)+'.'+mime)
	var dataBuffer = new Buffer(base64Data, 'base64');
	return new Promise((resolve,reject)=>{
		fs.writeFile(url, dataBuffer, function(err) {
		    if(err){
		      reject('图片保存失败')
		    }else{
		     resolve({
					 state:200,
					 url:path.join('public','images','heads',Namen(name)+'.'+mime)
				 })
		    }
		});
	})
}

module.exports=saveImg